from asyncio import create_task, gather, run
from asyncio import sleep as async_sleep
from adafruit_httpserver import (
    REQUEST_HANDLED_RESPONSE_SENT,
    FileResponse,
    Request,
    Response,
    Server,
)
from adafruit_httpserver import DELETE, GET, POST,OPTIONS, PUT, JSONResponse
import socketpool
import wifi
import secrets

#If client request http://HOST:PORT/file successful. MAYBE_EXEC will fill.
MAYBE_EXEC = {}
SSID = secrets.secrets["ssid"]
PASSWD = secrets.secrets["passwd"]
while True:
    try:
        wifi.radio.connect(SSID, PASSWD)
        print(wifi.radio.ipv4_address)
        break
    except Exception as e:
        if wifi.radio.connected:
            break
        print(e)
        print("retry")
        continue
ADDR = (str(wifi.radio.ipv4_address), 5000)

with open("pico.html", "r") as f:
    html = f.read()
    html_content = html.replace("jihaixuan",f"http://{ADDR[0]}:{ADDR[1]}/file/")

pool = socketpool.SocketPool(wifi.radio)
server = Server(pool, "/static", debug=True)
server.headers = {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Methods": "POST,OPTIONS,GET",
    "Access-Control-Allow-Headers": "*",
}

@server.route("/")
def base(request: Request):
    """
    Serve the default index.html file.
    """
    return Response(request, body=html_content, content_type="text/html")

@server.route("/file/",[POST])
def file_upload(request: Request):
    global MAYBE_EXEC
    print("file_upload",request.method)

    if request.method == "POST":
        try:
            file = request.json()
            MAYBE_EXEC = file
            return JSONResponse(request, {"status": "success"})
        except Exception as e:
            print(f"Error: {e}")
            return JSONResponse(request, {"status": "error", "message": str(e)})
# Start the server.
server.start(str(wifi.radio.ipv4_address))


async def handle_http_requests():
    while True:
        # Process any waiting requests
        pool_result = server.poll()

        if pool_result == REQUEST_HANDLED_RESPONSE_SENT:
            # Do something only after handling a request
            pass
        await async_sleep(0)


async def do_something_useful():
    while True:
        # Do something useful in this section,
        # for example read a sensor and capture an average,
        # or a running total of the last 10 samples
        global MAYBE_EXEC
        try:
            if MAYBE_EXEC["file"]:
                exec(MAYBE_EXEC["file"])
                MAYBE_EXEC = {}
        except Exception as e:
            #print(e)
            pass

        await async_sleep(1)

        # If you want you can stop the server by calling server.stop() anywhere in your code





async def main():
    await gather(
        create_task(handle_http_requests()),
        create_task(do_something_useful()),
    )

print("start main")
run(main())
